package com.wh.base.aop;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import com.wh.base.aop.documented.OperLog;
import com.wh.base.sys.log.entity.Log;
import com.wh.base.sys.log.service.LogService;
import com.wh.base.sys.user.service.UserService;
import com.wh.base.util.IpUtil;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONUtil;

/**
 * 切面处理类，操作日志异常日志记录处理
 *
 * @author wanghong
 */
@Aspect
@Component
public class WebLogAspect {

    @Autowired
    private LogService logService;
    
    @Autowired
    private UserService userService;

    // 设置操作日志切入点 记录操作日志 在注解的位置切入代码
    @Pointcut("@annotation(com.wh.base.aop.documented.OperLog)")
    public void operatePointCut() {
    }


    /**
     * 设置操作异常切入点记录异常日志 扫描所有controller包下操作
     */
    @Pointcut("execution(* com.wh.base..*.controller..*.*(..))")
    public void operateExceptionPoinCut() {
    }


    /**
     * 返回通知
     * 拦截用户操作日志，连接点正常执行完成后执行， 如果连接点抛出异常，则不会执行
     *
     * @param joinPoint 切入点
     * @param keys      返回结果
     */
    @AfterReturning(value = "operatePointCut()", returning = "keys")
    public void saveOperLog(JoinPoint joinPoint, Object keys) {
        saveLogInfo(joinPoint, keys, null);
    }

    /**
     * 异常返回通知，用于拦截异常日志信息 连接点抛出异常后执行
     *
     * @param joinPoint 切入点
     * @param e         异常信息
     */
    @AfterThrowing(pointcut = "operateExceptionPoinCut()", throwing = "e")
    public void saveExceptionLog(JoinPoint joinPoint, Throwable e) {
        saveLogInfo(joinPoint, null, e);
    }


    /**
     * 保存日志信息
     *
     * @param joinPoint 切点
     * @param keys      返回值
     * @param e         异常类
     */
    public void saveLogInfo(JoinPoint joinPoint, Object keys, Throwable e) {
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);
        Log sysLog = new Log();
        try {
            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            // 获取切入点所在的方法
            Method method = signature.getMethod();
            // 获取请求的类名
            String className = joinPoint.getTarget().getClass().getName();
            // 获取请求的方法名
            String methodName = method.getName();
            methodName = className + "." + methodName;
            sysLog.setOperMethod(methodName); // 请求方法
            // 请求的参数
            Map<String, String> rtnMap = converMap(request.getParameterMap());
            // 过滤密码, 不在日志中显示
            if(rtnMap.containsKey("password")) {
            	rtnMap.remove("password");
            }
            if(rtnMap.containsKey("newPassword")) {
            	rtnMap.remove("newPassword");
            }
            if(rtnMap.containsKey("confirmPassword")) {
            	rtnMap.remove("confirmPassword");
            }
            
            
            // 将参数所在的数组转换成json
            String params = JSONUtil.toJsonStr(rtnMap);

            // 获取操作
            OperLog opLog = method.getAnnotation(OperLog.class);
            if (opLog != null) {
                String operModul = opLog.operModul();
                String operType = opLog.operType();
                String operDesc = opLog.operDesc();
                sysLog.setOperModule(operModul);
                sysLog.setOperType(operType);
                sysLog.setOperDesc(operDesc);
            }

            if (e != null) {
                // 异常名称
                sysLog.setExceptionName(e.getClass().getName());
                // 异常信息
                sysLog.setExceptionMessage(stackTraceToString(e.getClass().getName(), e.getMessage(), e.getStackTrace()));
            }
            String username = "admin";
            if(StpUtil.isLogin()) {
            	username = userService.getUser().getUsername();
            }

            sysLog.setRequestParam(params);
            sysLog.setResponseParam(JSONUtil.toJsonStr(keys));
            sysLog.setIp(IpUtil.getIpAddr(request));
            sysLog.setUri(request.getRequestURI());
            sysLog.setCreateUser(username);
            sysLog.setCreateTime(new Date());
            sysLog.setRequestState(e == null ? "1" : "2");
            //插入数据到数据库
            logService.save(sysLog);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    /**
     * 转换request 请求参数
     *
     * @param paramMap request获取的参数数组
     */
    public Map<String, String> converMap(Map<String, String[]> paramMap) {
        Map<String, String> rtnMap = new HashMap<String, String>();
        for (String key : paramMap.keySet()) {
            rtnMap.put(key, paramMap.get(key)[0]);
        }
        return rtnMap;
    }

    /**
     * 转换异常信息为字符串
     *
     * @param exceptionName    异常名称
     * @param exceptionMessage 异常信息
     * @param elements         堆栈信息
     */
    public String stackTraceToString(String exceptionName, String exceptionMessage, StackTraceElement[] elements) {
        StringBuffer strbuff = new StringBuffer();
        for (StackTraceElement stet : elements) {
            strbuff.append(stet + "\n");
        }
        String message = exceptionName + ":" + exceptionMessage + "\n\t" + strbuff.toString();
        return message;
    }
}
